package cn.com.pc.content.util;

import cn.com.pc.content.domain.Site;
import cn.com.pc.content.domain.content.Content;
import cn.com.pc.content.domain.content.ContentType;
import com.google.common.base.Splitter;
import lombok.experimental.UtilityClass;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author hjlu
 * @create 2021/4/27 下午3:37
 */
@UtilityClass
public class ContentUtils {

    public String getIndexName(Site site, ContentType contentType) {
        return "pcp_" + site.getName() + "_" + contentType.getName();
    }

    public String getIndexName(Site site) {
        List<String> indexNames = new ArrayList<>();
        for (ContentType each : ContentType.getContentTypes(site)) {
            indexNames.add(getIndexName(site, each));
        }
        return String.join(",", indexNames);
    }

    public String getMongoCollection(ContentType contentType) {
        return "pcp_" + contentType.getName();
    }


    /**
     * 根据内容生成url
     *
     * @param content
     * @param contentType
     * @return
     */
    public String getUrlFromContent(Content content, ContentType contentType) {
        return "/api" + contentType.getApiPrefix() + "/" + content.getId() + "?contentType=" + contentType.name() + "&updatedAt=" + content.getUpdatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

    public String getParamFromUrl(String url, String key) {
        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
        Map<String, String> querys = Splitter.on("&").withKeyValueSeparator("=").split(uri.getQuery());
        return querys.get(key);
    }

    public ContentType getContentTypeFromUrl(String url) {
        String contentType = getParamFromUrl(url, "contentType");
        return ContentType.valueOf(contentType == null ? "Other" : contentType);
    }

    public String getContentIdFromUrl(String url) {
        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
        String[] split = uri.getPath().split("/");
        return split[split.length - 1];
    }

}
